package cn.kgc.springboot.service.impl;

import cn.kgc.springboot.entity.MessageBoard;
import cn.kgc.springboot.mapper.MessageMapper;
import cn.kgc.springboot.service.MessageService;
import cn.kgc.springboot.util.JsonUtil;
import cn.kgc.springboot.util.RedisUtil;
import cn.kgc.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mosin
 * date 2021/12/16
 * @version 1.0
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result addMessage(MessageBoard messageBoard) { // 完成留言的持久化  同时保存一份到redis
       int line =   messageMapper.insertMessage(messageBoard);
       Result result =   Result.builder().build();
       if(line>0){  // 保存数据到redis
           redisUtil.setListValue("commit", JsonUtil.toString(messageBoard));
           result.setCode(200);
           result.setMsg("留言保存成功");
       }
        return result;
    }

    //暂存信息
    @Override
    public Result addTempMessage(MessageBoard messageBoard) {
        Result result = Result.builder().build();
        try {
            redisUtil.setValue(messageBoard.getDeviceId(), JsonUtil.toString(messageBoard));
            result.setCode(200);
            result.setMsg("留言暂存成功!");
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("留言暂存失败");
        }
        return result;
    }

    @Override
    public Result findTemp(String remoteAddr) {

        String value = redisUtil.getValue(remoteAddr);
        Object object = JsonUtil.toObject(value);

        Result result = Result.builder().build();

        result.setCode(200);
        result.setData(object);
        result.setCount(1);
        result.setMsg("查询暂存信息成功!");
        return result;
    }

    @Override
    public Result findAll() { // 查询所有 先从 redis查询 redis没有则从mysql数据库中查询

        List<String> commit = redisUtil.getAllListValues("commit");
        Result  result = Result.builder().build();
        ArrayList<Object> list = new ArrayList<>();
        if(commit.size()>0){ //遍历集合
            commit.forEach(message->{
                list.add( JsonUtil.toObject(message));
            });

            result.setMsg("DATA  from  Redis");
            result.setCode(200);
            result.setCount(list.size());
            result.setData(list);

        }else{
            List<MessageBoard> messageBoards = messageMapper.queryAll();
            //将数据放入redis
            messageBoards.forEach(message->{
                redisUtil.setListValue("commit", JsonUtil.toString(message));
            });
            result.setMsg("DATA  from  MYSQL");
            result.setCode(200);
            result.setCount(messageBoards.size());
            result.setData(messageBoards);

        }
        return result;
    }
}
